package com.bwie.record.task;

import com.alibaba.fastjson.JSON;
import com.bwie.record.domain.DataOne;
import com.bwie.record.domain.DataThree;
import com.bwie.record.domain.DataTwo;
import com.bwie.record.service.DataOneService;
import com.bwie.record.service.DataThreeService;
import com.bwie.record.service.DataTwoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Component
public class DataTask {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private DataOneService dataOneService;

    @Autowired
    private DataTwoService dataTwoService;

    @Autowired
    private DataThreeService dataThreeService;

    @Scheduled(cron = "0 0/5 * * * *")
    public void processData() {
        // 1. 查询最新的数据时间
        Object o = redisTemplate.opsForValue().get("dataLastTime");
        Date lastTime = JSON.parseObject(JSON.toJSONString(o), Date.class);
        // 2. 根据最新时间查询dataOne的数据
        List<DataOne> dataOnes;
        if (lastTime == null) {
            dataOnes = dataOneService.findAll();
        } else {
            dataOnes = dataOneService.findByTimestampGreaterThanEqualOrderByTimestampAsc(String.valueOf(lastTime));
        }

        // 3. 遍历dataOnes，根据id去dataTwo和dataThree进行查询
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (DataOne dataOne : dataOnes) {
            String id = dataOne.getId();
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                DataTwo dataTwo = dataTwoService.findById(id);
                DataThree dataThree = dataThreeService.getDataThreeById(id);

                if (dataTwo == null || dataThree == null) {
                    return;
                }
                // 4. 保存图片并获取图片名称
                String imageName = saveImage(dataOne);

                // 5. 拼接字符串写入到txt文件中
                writeToFile(dataOne, dataTwo, dataThree, imageName);
            });
            futures.add(future);
        }

        // 6. 等待所有异步任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        // 7. 更新redis中的dataLastTime为最新的时间
        if (!CollectionUtils.isEmpty(dataOnes)) {
            Date latestTime = dataOnes.stream()
                    .map(DataOne::getTime)
                    .max(Date::compareTo)
                    .orElse(null);
            if (latestTime != null) {
                redisTemplate.opsForValue().set("dataLastTime", latestTime, 30, TimeUnit.MINUTES);
            }
        }
    }

    private String saveImage(DataOne dataOne) {
        // 实现图片保存逻辑，返回图片名称
        return "image_name";
    }

    private void writeToFile(DataOne dataOne, DataTwo dataTwo, DataThree dataThree, String imageName) {
        // 实现将dataOne、2、3及图片名称拼接字符串写入到txt文件的逻辑
        try (FileWriter writer = new FileWriter(Paths.get("output.txt").toFile(), true)) {
            writer.write(dataOne.toString() + "\t" + dataTwo.toString() + "\t" + dataThree.toString() + "\t" + imageName + " ");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
